package logic

import (
	"bytes"
	"errors"
	"fmt"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"image"
	"struggle/dao/mysql"
	"struggle/model"
	"struggle/pkg/util"
	"time"
)

var allowImage = map[string]bool{
	"png":  true,
	"jpg":  true,
	"jpeg": true,
	"gif":  true,
}

type imageLogic struct{}

var DefaultImage = imageLogic{}

func (m imageLogic) Create(img []byte) (*model.Image, error) {
	config, format, err := image.DecodeConfig(bytes.NewReader(img))
	zap.L().Debug("format", zap.Any("format", format))

	if err != nil {
		zap.L().Error("imageLogic failed", zap.Error(err))
		return nil, err
	}
	if _, ok := allowImage[format]; !ok {
		zap.L().Error("imageLogic failed 图片格式非法", zap.Error(err))
		return nil, errors.New("图片格式非法")
	}
	md5 := util.Md5Buffer(img)
	imageStore, _ := mysql.DefaultImage.FindOne(md5)
	if imageStore.ID > 0 {
		return imageStore, nil
	}

	now := time.Now()
	filePath := fmt.Sprintf("/%s/%d/%d/%d", viper.GetString("image.save_path"), now.Year(), now.Month(), now.Day())
	imageStore = &model.Image{
		Md5:    md5,
		Path:   filePath + md5 + "." + format,
		Size:   len(img),
		Width:  config.Width,
		Height: config.Height,
	}
	err = mysql.DefaultImage.Create(imageStore)
	return imageStore, nil
}
